<template>
    <div class="page">
        <div>
            <div class="crumbs">
                <el-breadcrumb separator="/">
                    <el-breadcrumb-item><i class="el-icon-menu"></i> 原子管理</el-breadcrumb-item>
                    <el-breadcrumb-item>添加原子</el-breadcrumb-item>
                </el-breadcrumb>
            </div>
            <el-form :model="formData" :rules="rules" ref="formData" label-width="100px">
                <el-form-item label="原子名称" prop="name">
                    <el-input v-model="formData.name"></el-input>
                </el-form-item>
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="属性" prop="type">
                            <el-select v-model="formData.type" placeholder="请选择" style="width: 100%;">
                                <el-option
                                        v-for="item in typeOptions"
                                        :label="item.label"
                                        :value="item.value"
                                        :key="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="请求类型" prop="kind">
                            <el-select v-model="formData.kind" placeholder="请选择" style="width: 100%;">
                                <el-option
                                        v-for="item in kindOptions"
                                        :label="item.name"
                                        :value="item.id"
                                        :key="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="类型" prop="category_id">
                            <el-select v-model="formData.category_id" placeholder="请选择" style="width: 100%;">
                                <el-option
                                        v-for="item in categoryOptions"
                                        :label="item.name"
                                        :value="item.id"
                                        :key="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <!--<el-row v-if='formData.type == 2'>
            		<el-col :span="8">
		                <el-form-item prop="rowStyle">
		                    <el-checkbox v-model="formData.rowStyle">竖向表格</el-checkbox>
		                </el-form-item>
                    </el-col>
                    <el-col :span="8">
		                <el-form-item prop="mergeHeader">
		                    <el-checkbox v-model="formData.mergeHeader">显示合并格表头</el-checkbox>
		                </el-form-item>
                    </el-col>
                    <el-col :span="8">
		                <el-form-item label="合并格名称" prop="mergeName" v-if='formData.mergeHeader'>
		                    <el-input v-model="formData.mergeName"></el-input>
		                </el-form-item>
	                </el-col>
            	</el-row>-->
                <!--<div v-for="item in subAtoms">
                  <el-form-item label="后台接口" label-width="100px">
                    <el-input v-model="item.urls" auto-complete="off"></el-input>
                  </el-form-item>
                  <el-row>
                      <el-col :span="12">
                          <el-form-item label="固定请求参数" label-width="100px">
                              <el-input
                                      type="textarea"
                                      :autosize="{ minRows: 2}"
                                      placeholder="请输入一个正确的json数据"
                                      v-model="item.fixed_req_params">
                              </el-input>
                          </el-form-item>
                      </el-col>
                      <el-col :span="12">
                          <el-form-item label="变动请求参数" label-width="100px">
                              <el-input
                                      type="textarea"
                                      :autosize="{ minRows: 2}"
                                      placeholder="请输入一个正确的json数据"
                                      v-model="item.auto_req_params">
                              </el-input>
                          </el-form-item>
                      </el-col>
                  </el-row>
                </div>
                <div style="margin-bottom: 20px;">
                  <i class="el-icon-plus" style="font-size: 26px; position: relative; left: 50px;" title="添加接口" @click="add"></i>
                </div>-->
            </el-form>
            <div style="padding-left: 35px;margin-bottom: 20px;">
	            <el-row>
	            	<span style="font-size: 14px;color: #606266;line-height: 40px;">接口信息</span>
	            	<el-button type="text" icon="el-icon-circle-plus-outline" @click="add" style="float: right;">添加接口</el-button>
	            </el-row>
	          	<el-table :data="subAtoms" border style="width: 100%" :header-cell-style="{'background':'#eef1f6','color':'#1f2d3d'}">
				    <el-table-column label="接口地址" min-width="180">
				      	<template slot-scope="scope">
				      		<el-input v-model="scope.row.urls" type="textarea" :autosize="{ minRows: 2}"></el-input>
				      	</template>
				    </el-table-column>
				    <el-table-column label="固定请求参数" min-width="300">
				      	<template slot-scope="scope">
				      		<el-input v-model="scope.row.fixed_req_params" placeholder="请输入一个正确的json数据" type="textarea" :autosize="{ minRows: 2}"></el-input>
				      	</template>
				    </el-table-column>
				    <el-table-column label="变动请求参数" min-width="300">
				      	<template slot-scope="scope">
				      		<el-input v-model="scope.row.auto_req_params" placeholder="请输入一个正确的json数据" type="textarea" :autosize="{ minRows: 2}"></el-input>
				      	</template>
				    </el-table-column>
				    <el-table-column label="操作" width="100">
				      	<template slot-scope="scope">
				        	<el-button @click.native.prevent="deleteRow(scope.$index, subAtoms)" type="text" size="small">移除</el-button>
				      	</template>
				    </el-table-column>
			  	</el-table>
		  	</div>
            <div slot="footer" class="dialog-footer" style="text-align: center;">
                <el-button @click="backList">返回列表页</el-button>
                <el-button @click="toEditAtomParameter" v-if="formData.id" >编辑原子参数</el-button>
                <el-button type="primary" @click="addOrEditSubmit('formData')">确 定</el-button>
            </div>
        </div>
        <EditAtomParameter :data="editAtomParameterObj.data" v-if="showEditAtomParameterPannel" @closedialog="closeEditAtomParameterPannel"></EditAtomParameter>
    </div>
</template>
<script>
import api from "../../../api/api";
import util from "../../../common/util";
import EditAtomParameter from "./EditAtomParameter.vue";

export default {
  props: {
    data: null
  },
  components: {
    EditAtomParameter
  },
  data() {
    return {
      	formData: {
	        id: "",
	        name: "",
	        type: 1,
	        kind: 1,
	        category_id: ""
      	},
      	subAtoms: [
	        {
	          	urls: "http://query.wedengta.com/query",
	          	fixed_req_params: JSON.stringify({
	            	func: "db_spider.LONGHU_STOCK_DETAILS"
	          	}),
	          	auto_req_params: JSON.stringify({
	            	conds: [{ date: "2017-10-13", dt_code: "0101600499" }]
	          	})
	        }
      	],
      	kindOptions: [
	        {
	          id: 1,
	          name: "并行请求"
	        },
	        {
	          id: 2,
	          name: "串行请求"
	        }        
      	],
      	typeOptions: [
	        {
	          value: 1,
	          label: "文本"
	        },
	        {
	          value: 2,
	          label: "表格"
	        },
			{
	          value: 6,
	          label: "竖向表格"
	       	},
	        {
	          value: 21,
	          label: "表格(原子名称)"
	        },
	        {
	          value: 3,
	          label: "树形图(左右)"
	        },
	        {
	          value: 4,
	          label: "柱状图"
	        },
			{
	          value: 51,
	          label: "饼图(默认数据)"
	       	},
	    	{
	          value: 5,
	          label: "饼图(自选数据)"
	       	}
      	],
      	categoryOptions: [],
      	showEditAtomParameterPannel: false,
      	editAtomParameterObj: {
        	data: null
      	},
      	rules: {
          	name: [
	            { required: true, message: '请输入原子名称', trigger: 'blur' },
          	],
          	category_id: [
	            { required: true, message: '请选择原子类型', trigger: 'change' }
          	]
 		}
    }
  },
  methods: {
    //添加更新
    addOrEditSubmit(formName) {
        this.$refs[formName].validate((valid) => {
          	if (valid) {
          		let _this = this;
          		_this.checkJson(_this.subAtoms).then(function (tar) {
			        _this.formData.urls = [];
			        _this.formData.fixed_req_params = [];
			        _this.formData.auto_req_params = [];
			        _this.subAtoms.forEach(element => {
			          	_this.formData.urls.push(element.urls);
			          	_this.formData.fixed_req_params.push(element.fixed_req_params);
			          	_this.formData.auto_req_params.push(element.auto_req_params);
			        });
			        _this.formData.urls = _this.formData.urls.join(",");
			        _this.formData.fixed_req_params = _this.formData.fixed_req_params.join("&&");
			        _this.formData.auto_req_params = _this.formData.auto_req_params.join("&&");
			        let para = {
			          	form: _this.formData,
			          	tableName: "atom"
			        };
			        api.addOrEditSubmit(para).then(res => {
			            if (res.ret == 0) {
			              	_this.$message({ type: "success", message: "添加或者更新原子成功！" });
			              	_this.$emit("refresh");
			            } else {
			              	_this.$message({ type: "error", message: "添加或者更新原子失败！" });
			            }
			      	}).catch(e => {
			            _this.$message({ type: "error", message: "添加或者更新原子失败！" });
			      	});
			    }).catch(function (err) {
			    	_this.$message({ type: "error", message: err.message });
			    })
          	} else {
	            console.log('error submit!!');
	            return false;
          	}
        });
    },
    checkJson(arr){
    	return new Promise(function (resolve, reject) {
    		arr.forEach(item => {
			  	try {
				    JSON.parse(item.fixed_req_params);
				    JSON.parse(item.auto_req_params);
			  	} catch (err) {
				    reject(new Error('接口参数格式错误'));
			  	}
    		});
    		resolve();
	  	})
    },
    add() {
      this.subAtoms.push({
        urls: "http://query.wedengta.com/query",
        fixed_req_params: JSON.stringify({ func: "db_spider.LONGHU_STOCK_DETAILS" }),
        auto_req_params: JSON.stringify({ conds: [{ date: "2017-10-13", dt_code: "0101600499" }] })
      })
    },
  	deleteRow(index, rows) {
  		if(rows.length > 1){
  			rows.splice(index, 1);
  		} else {
          	this.$message({ type: "warning", message: "请最少保留一个接口数据" });
  		}
  	},
    //获取用户列表
    getCategoryList() {
      let para = {
        currentPage: 0,
        pageNumb: 10000,
        wheres: JSON.stringify([
          {
            type: "1",
            key: "status",
            value: 1
          }
        ]),
        order: "id",
        tableName: "atom_category"
      };

      let that = this;
      api
        .getList(para)
        .then(res => {
          if (res.ret == 0) {
            that.categoryOptions = res.data.dataList;
          } else {
            that.$message({
              type: "error",
              message: "获取原子类型失败"
            });
          }
        })
        .catch(e => {
          that.$message({
            type: "error",
            message: "获取原子类型失败"
          });
        });
    },
    backList() {
      this.$emit("close");
    },
    closeEditAtomParameterPannel() {
      this.showEditAtomParameterPannel = false;
      //this.editShow = true;
    },
    toEditAtomParameter() {
      this.editAtomParameterObj.data = {
        key_params: this.formData.key_params,
        id: this.formData.id,
        kind: this.formData.kind,
        type: this.formData.type,
        subAtoms: this.subAtoms
      };
      this.showEditAtomParameterPannel = true;
      //this.editShow = false;
    }
  },
  created() {
    if (this.data) {
      // this.formData = this.data;
      this.formData.id = this.data.id;
      this.formData.category_id = this.data.category_id;
      this.formData.name = this.data.name;
      this.formData.kind = this.data.kind;
      this.formData.type = this.data.type;
      this.subAtoms = [];
      this.formData.urls = this.data.urls.split(",");
      this.formData.fixed_req_params = this.data.fixed_req_params.split("&&");
      this.formData.auto_req_params = this.data.auto_req_params.split("&&");
      for (let index = 0; index < this.formData.urls.length; index++) {
        const element = this.formData.urls[index];
        this.subAtoms.push({
          urls: element,
          fixed_req_params: this.formData.fixed_req_params[index],
          auto_req_params: this.formData.auto_req_params[index]
        });
      }
    }
  },
  mounted() {
    this.getCategoryList();
  }
};
</script>
